<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applyUserId">
            <UserSelect v-model="form.applyUserId" :placeholder="$t('申请人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <DatePicker
              v-model="form.applyTime"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同名称')" prop="contractName">
            <el-input v-model="form.contractName" :placeholder="$t('合同名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('对方签约主体')" prop="otherSignMain">
            <el-input v-model="form.otherSignMain" :placeholder="$t('对方签约主体')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('文件份数')" prop="fileCount">
            <el-input-number v-model="form.fileCount" :placeholder="$t('文件份数')" show-word-limit :max="10000000" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('加盖骑缝章')">
            <el-radio-group v-model="form.sealRidingSeam" size="small">
              <el-radio-button
                v-for="dict in yesNoOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('合同摘要')" prop="contractAbstract">
            <el-input v-model="form.contractAbstract" type="textarea" :placeholder="$t('合同摘要')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--用印明细-->
      <div class="area-header">
        <span class="area-header-title">{{ $t('用印明细') }}</span>
      </div>
      <el-table :data="form.oaSealDetailList" border class="nowrapTable formTable">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('用印主体类型')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('用印主体类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMainType'" :rules="oaSealDetailListRules.investMainType">
              <dictSelect
                v-model="scope.row.investMainType"
                :clearable="true"
                dictionary="main_body_type_seal"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('用印主体')" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('用印主体') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMain'" :rules="oaSealDetailListRules.investMain">
              <MainBodySelect
                v-model="scope.row.investMain"
                :parameters="scope.row.investMainType"
                @change="changeSealInvest"
              />
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column :label="$t('印章类型')">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('印章类型') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.sealType'" :rules="oaSealDetailListRules.sealType">
              <el-select
                v-model="scope.row.sealType"
                multiple
                :placeholder="$t('请选择')"
                @change="changeSealType(scope.row.investMain)"
              >
                <el-option
                  v-for="dict in sealTypeDict"
                  :key="dict.dictValue"
                  :label="$t(dict.dictLabel)"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column :label="$t('备注')" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.remark'" :rules="oaSealDetailListRules.remark">
              <el-input v-model="scope.row.remark" type="textarea" maxlength="2000" show-word-limit :autosize="{ minRows:1,maxRows:10 }" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
          <template slot-scope="scope">
            <el-button v-hasPermi="['oa:seal:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!otherBtnHide" class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t('添加明细') }}</el-button>
      </div>
      <!--文件-->
      <FileTable
        :file-title="$t('用印附件信息')"
        :list.sync="form.fileList"
        data-type="lp_raise_contract_sign"
        :business-id="form.projectOrFund"
        :btn-show="!otherBtnHide"
        :slot-input-box-data="slotInputBoxData"
        @changeSlotInput="changeSlotInput"
      />
      <FileTable
        :file-title="$t('其他附件信息')"
        :list.sync="form.fileListOther"
        data-type="lp_raise_contract"
        :business-id="form.projectOrFund"
        :btn-show="!otherBtnHide"
      />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="lp:raiseContractSign" />
    </div>
  </div>
</template>

<script>
    import { saveLpRaiseContractSign, getLpRaiseContractSign } from '@/api/fund/raiseContractSign/lpRaiseContractSign'
    import MainBodySelect from '@/components/MainBodySelect/index.vue'
    import { ruoyiFloat } from '@/utils/ruoyi'
    import { deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
    import { formatFileListSlotValue, showFileListSlotValue } from '@/api/file/fileTable/fileTableSlot'
    export default {
      components: { MainBodySelect },
        data() {
            return {
                // 表单参数
                form: {},
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 表单校验
                rules: {
                    actTitle: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                    applyUserId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                    applyTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                    contractName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                    otherSignMain: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                    fileCount: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 校验用印明细不能为空
                oaSealDetailListRules: {
                  investMainType: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                  investMain: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
                  sealType: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
                },
                yesNoOptions: [],
                slotInputBoxData: [],
                fileSealTypeOption: {},
                fileInvestIdOptions: [],
                sealTypeDict: [],
                // 操作按钮默认不展示
                buttonShow: true
            }
        },
        created() {
            this.getDicts('seal_type').then(response => {
              this.sealTypeDict = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
              this.yesNoOptions = response.data
            })
        },
        mounted() {
          this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                this.slotInputBoxData = this.initFileFieldDefault()
                if (data != null && data.id !== undefined) {
                    getLpRaiseContractSign(data.id).then(response => {
                        this.form = response.data
                        this.initFileFieldValue()
                        this.loading = false
                    }).catch(() => {
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    lpId: this.$route.query.lpId,
                    actTitle: undefined,
                    actId: undefined,
                    actStatus: undefined,
                    applyUserId: this.$store.state.user.userId,
                    applyTime: new Date(),
                    contractName: undefined,
                    otherSignMain: undefined,
                    fileCount: undefined,
                    sealRidingSeam: undefined,
                    contractAbstract: undefined,
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                    fileList: [],
                    fileListOther: [],
                    oaSealDetailList: []
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                    this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
          // 印章类型变化
          changeSealType(investMain) {
            console.log(investMain)
            this.initFileFieldValue()
          },
          // 给动态组件初始化字段
          initFileFieldValue() {
            this.slotInputBoxData = []
            this.fileInvestIdOptions = []
            this.initSlotInvestTypeDict()
            this.slotInputBoxData = this.initFileFieldDefault()
            // 加载附件绑定的
            if (this.form.fileList) {
              // 调整
              console.log('tiaozheng')
              this.form.fileList.forEach((item, index) => {
                if (this.isEmpty(item.slotData)) {
                  item.slotData = this.initFileFieldDefault()
                } else {
                  // 回显
                  var tempSlotData = this.initFileFieldDefault()
                  item.slotData && item.slotData.forEach((slot) => {
                    // 回显附主体章
                    tempSlotData && tempSlotData.forEach(data => {
                      if (data.model === slot.model && item.id === slot.dataId) {
                        data.dataId = slot.dataId
                        if (slot.model === 'investSealType') {
                          data.value = this.getSelectValueArr(slot.value)
                        }
                        // 回显印章数量
                        if (slot.model === 'copies') {
                          if (!this.isEmpty(slot.value)) {
                            data.value = parseInt(slot.value)
                          }
                        }
                      }
                    })
                  })
                  this.$set(this.form.fileList[index], 'slotData', tempSlotData)
                }
              })
              this.$forceUpdate()
            }
          },
          initFileFieldDefault() {
            return [
              { type: 'select', label: this.$t('主体及印章'), model: 'investSealType', placeholder: this.$t('请选择'), minWidth: 160, multiple: true, selectOptions: this.fileInvestIdOptions, required: true, value: [] },
              { type: 'input', label: this.$t('份数'), model: 'copies', placeholder: this.$t('份数'), minWidth: 80, required: true, value: undefined }
            ]
          },
          // 初始化动态字段下拉
          initSlotInvestTypeDict() {
            this.form.oaSealDetailList && this.form.oaSealDetailList.forEach((item) => {
              item.sealType && item.sealType.forEach(type => {
                var dictLabel = item.investMainName
                // 如果dictLabel最后一个字符是中文)则去不加空格
                if (dictLabel && dictLabel.charAt(dictLabel.length - 1) !== '）') {
                  dictLabel = dictLabel + ' '
                }
                this.fileInvestIdOptions.push({
                  dictValue: item.investMain + '_' + type,
                  dictLabel: dictLabel + '一 ' + this.translationDictSealType(type)
                })
              })
            })
          },
          // 翻译字典
          translationDictSealType(val) {
            var find = this.sealTypeDict.find(obj => obj.dictValue === val)
            if (find) {
              return find.dictLabel
            }
            return ''
          },
          // 修改主题时, 判断选中的主体中是否依然存在, 不存在就清空
          getSelectValueArr(value) {
            console.log('11111111111111111')
            var result = []
            var arr = []
            try {
              if (typeof value === 'string') {
                arr = JSON.parse(value)
              } else {
                arr = value
              }
              arr && arr.forEach(item => {
                this.fileInvestIdOptions.forEach(sub => {
                  if (item === sub.dictValue) {
                    result.push(item)
                  }
                })
              })
              return result
            } catch (e) {
              console.log(e)
            }
            return result
          },
          // 用印明细
          addPayment() {
            const row = {
              id: undefined,
              investMainType: '',
              investMain: '',
              sealType: '',
              remark: ''
            }
            if (!(this.form.oaSealDetailList instanceof Array)) {
              this.$set(this.form, 'oaSealDetailList', [])
            }
            this.$nextTick(() => {
              this.form.oaSealDetailList.push(row)
            })
          },
          // 删除用印明细
          delHandle(index, row) {
            // eslint-disable-next-line no-undef
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return deleteOaSealDetail(id)
                }).then(() => {
                this.form.oaSealDetailList.splice(index, 1)
                this.changeSealInvest()
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaSealDetailList.splice(index, 1)
              this.changeSealInvest()
            }
          },
            // 为主表累计分数
            changeSlotInput(data) {
              // 是数据累计. 不是数据清空输入内容
              data.e = Number(data.e)
              if (typeof data.e === 'number' && !isNaN(data.e)) {
                var temp = 0
                this.form.fileList && this.form.fileList.forEach((item, index) => {
                  item.slotData && item.slotData.forEach(item2 => {
                    if (item2.model === 'copies') {
                      if (index === data.index && data.e !== '' && !this.isEmpty(data.e)) {
                        temp += ruoyiFloat().formatNum(data.e) === Infinity ? 0 : ruoyiFloat().formatNum(data.e)
                      } else {
                        temp += ruoyiFloat().formatNum(item2.value) === Infinity ? 0 : ruoyiFloat().formatNum(item2.value)
                      }
                    }
                  })
                })
                this.$set(this.form, 'fileCount', temp)
              } else {
                this.form.fileList && this.form.fileList.forEach((item, index) => {
                  item.slotData && item.slotData.forEach((item2, index2) => {
                    if (item2.model === 'copies') {
                      if (index === data.index && data.e !== '' && !this.isEmpty(data.e)) {
                        // 清空输入的内容
                        this.form.fileList[index].slotData[index2].value = ''
                      }
                    }
                  })
                })
              }
            },
          /**
           * 用印主体变化
           */
          changeSealInvest(e, name) {
            var tempArr = []
            var flag = true
            this.form.oaSealDetailList && this.form.oaSealDetailList.some((item, index) => {
              if (name !== undefined && e === item.investMain) {
                item.investMainName = name
              }
              if (!tempArr.includes(item.investMain) || this.isEmpty(item.investMain)) {
                tempArr.push(item.investMain)
              } else {
                this.$nextTick(() => {
                  this.$set(this.form.oaSealDetailList[index], 'investMain', '')
                })
                flag = false
                return true
              }
            })
            this.$forceUpdate()
            if (flag) {
              this.initFileFieldValue()
            } else {
              this.msgWarning(this.$t('用印主体不能重复'))
            }
          },
          /** 提交按钮 */
          submitForm: function(type) {
            return new Promise((resolve, reject) => {
              var temp = this.form.oaSealDetailList
              if (temp === null || temp === undefined || temp === '' || temp <= 0) {
                this.msgError(this.$t('至少添加一条用印明细'))
              } else {
                this.$refs['form'].validate(valid => {
                  // 验证数据
                  if (valid) {
                    // 弹出遮罩层
                    this.loading = true
                    console.log(this.form)
                    // 保存数据
                    // 保存前将slot转为string
                    formatFileListSlotValue(this.form.fileList)
                    saveLpRaiseContractSign(this.form).then(response => {
                      showFileListSlotValue(this.form.fileList)
                      if (response.code === 200) {
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                          this.form.id = response.data.id
                          // 启动流程
                          this.startProcess(response.data.id)
                          // 点击的仅保存
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm()
                        }
                        resolve()
                      } else {
                        this.msgError(response.msg)
                        this.loading = false
                        reject()
                      }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    this.locationError(document)
                    reject()
                  }
                })
              }
            })
          },
            // 启动流程
           startProcess(dataId) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = this.form.actTitle
               // 业务表名
               processData.dataTable = 'lp_raise_contract_sign'
               // 业务ID
               processData.dataId = dataId
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/fund/raiseContractSign/lpRaiseContractSignForm'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = 'lp_raise_contract_sign'
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           }

        }

    }
</script>
